//#define _WINSOCK_DEPRECATED_NO_WARNINGS  1

#include "stdafx.h"
#include "stdio.h"
//#include <aclapi.h>
//#include "Thread.h"
#include "Sock.h"




CConnection::CConnection(int model, int type, int protocol)
	:nModel(model), nType(type), nProtocol(protocol)
{
	WSAStartup(MAKEWORD(2, 2), &wsaData);
	m_socket = new SOCKET();
	m_wsaData = new WSADATA();
	m_sock = new SOCKADDR_IN();
	//pThread = new CThread();
}


CConnection::~CConnection()
{
	WSACleanup();
	delete (m_socket);
	delete (m_wsaData);
	delete (m_sock);
	//delete (pThread);
}


int CConnection::init(char * addr)
{
	int ret = -1;
	*m_socket = socket(nModel, nType, nProtocol);
	printf("%d", WSAGetLastError());

	ret = bind(*m_socket, (SOCKADDR *)m_sock, sizeof(SOCKADDR_IN));
	if (ret == SOCKET_ERROR)
		printf("%d", WSAGetLastError());
	return 0;
}

void CConnection::listen(char * addr, int nPort)
{
	int ret = -1;
	//char buff[255];
	m_sock->sin_port = htons(nPort);
	//m_sock->sin_addr.s_addr = inet_addr (addr);
	ret = inet_pton(nModel, addr, &m_sock->sin_addr.s_addr);
	m_sock->sin_family = nModel;
	init(addr);
	ret = ::listen(*m_socket, SOMAXCONN);
	if (ret == SOCKET_ERROR)
		printf("%d", ret);
	//SOCKET s = accept(*m_socket, NULL, NULL);
	//return (s);
	//connect(m_socket,)
}

SOCKET CConnection::accept_conn()
{
	return(accept(*m_socket, NULL, NULL));

}

void CConnection::closeConnection()
{
	shutdown(*m_socket, SD_BOTH);
	closesocket(*m_socket);
}